package net.zjitc.controller;

/**
 * @author 何景航
 * @date 2024/12/25
 */

import net.zjitc.utils.APIResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
public class UploadController {
    private static final String UPLOAD_DIR = "src/main/resources/static/static/image/category/uploads/";
//private static final String UPLOAD_DIR = "upload/";

    @PostMapping("/upload")
    @CrossOrigin(origins = "*")
    public APIResponse uploadFile(@RequestParam("file") MultipartFile file) {
        APIResponse apiResponse = new APIResponse();
        if (file.isEmpty()) {
            apiResponse.error(1, "文件不能为空", null);
            return apiResponse;
        }
        try {
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            byte[] bytes = file.getBytes();
            String pathName = UUID.randomUUID()+file.getOriginalFilename();
            Path path = Paths.get(UPLOAD_DIR + pathName);
            Files.write(path, bytes);
            apiResponse.ok("上传成功", "static/image/category/uploads/"+pathName);
            return apiResponse;
        }catch(IOException e){
            e.printStackTrace();
            apiResponse.error(2, "上传失败", null);
            return apiResponse;
        }
    }
}

